﻿using System;
using System.Collections.Generic;
using System.Linq;
using VideoSeller.Business.Data;
using VideoSeller.Business.Data.Enums;

namespace VideoSeller.Web.Models
{
    //Просто трансляция, совещание, конференция
    // с паролем, без пароля
    // платно, бесплатно
	public class OnlineItemViewModel : BaseViewModel
	{
        private OnlineContent onlineContent = null;
        public int Id { get { return onlineContent.Id; } }

		public string Title { get; set; }

		public string Description { get; set; }

		public string ImageUrl { get; set; }
        public string CultureImage { get; set; }
        public string CultureCountry { get { return onlineContent.CultureCountry; } }
		public string DownloadUrl { get; set; }

		public int Likes { get; set; }

		public int Unlikes { get; set; }

		public int Views_online { get; set; }
        public int Views_anonce { get; set; }
        public int Views_history { get; set; }

		public decimal CollectedMoney { get; set; }
        public decimal CollectedMoneyExt { get; set; }

		public decimal Price { get; set; }

		public int TeamCount { get; set; }

		public int TeamRemainedCount { get; set; }

		public bool IsWaitingAnnouncement { get; set; }
        public int WaitCount { get; set; }
		public bool IsPaid { get; set; }

		public DateTime CreatedTime { get; set; }

		public DateTime BroadcastStart { get; set; }

		public DateTime BroadcastEnd { get; set; }

		public BroadcastType BroadcastType { get; set; }

		public OnlineContentType OnlineContentType { get; set; }

		public VideoContentType VideoContentType { get; set; }

		public Client Author { get; set; }

		public ContentListFilterViewModel FilterViewModel { get; set; }

		public bool IsAnonymous
		{
            get { return CurrentMembershipUser == null || CurrentMembershipUser.IsAnonymous; }
		}

		public bool UsePassword { get; set; }


		public IEnumerable<TeamDoc> TeamDocuments { get; set; }

		public IEnumerable<OnlineRating> Comments { get; set; }

		public List<string> Tags { get; set; }
        public String HistoryPath { get; set; }
        public String WowzaPath { get; set; }
		public ChatViewModel ChatModel { get; set; }
        public int m_AutorRating { get; set; }
        public int c_AutorRating { get; set; }
		public CommentsViewModel CommentsModel { get; set; }
        public bool useHistory { get; set; }
        public string lenHistory { get; set; }
        public long setTimer {get; set;}
        public int Claims { get; set; }
        public int maxViewers { get; set; }
        public int maxHours { get; set; }
        public decimal neenMoney { get; set; }
        public String country { get; set; }
        //список оффлайн файлов, сохраненных для совещания
		public IEnumerable<OnlineContentHistory> HistoryFiles { get; set; }
//        public IEnumerable<Setting> AllCamParams { get; set; }
		//список пользователей, подключенных к онлайн трансляции
		public IEnumerable<OnlineContentPlay> OnlinePlay { get; set; }
        public bool Active { get; set; }
        public bool isWaitingStart { get; set; }
        public IEnumerable<OnlineCategorization> Categories; 
        public bool AlreadyRate(Guid userId)
        {
            return onlineContent.AlreadyRate(userId);
        }
        public IEnumerable<Setting> AllCamParams { get; set; }
        public int currentViewers { get; set; }
        public String qualityString { get; set; }
		public OnlineItemViewModel(OnlineContent _onlineContent)
		{
            
            onlineContent = _onlineContent;
            isWaitingStart = onlineContent.isWaitingStart;
            Active = onlineContent.Active;
			Title = onlineContent.Title;
			Description = onlineContent.Description;
			ImageUrl = onlineContent.ImageUrl;
			CreatedTime = onlineContent.CreatedTime;
			TeamCount = onlineContent.TeamCount;
            VideoSeller.Business.Models.SettingsModel sm = new Business.Models.SettingsModel();
            HistoryPath = sm.GetSetting("HistoryPath").Value;
            WowzaPath = sm.GetSetting("WowzaPath").Value;
            AllCamParams = sm.QualityStrings;
            qualityString = sm.getQualityString(_onlineContent.QualityString);
            //
            maxViewers = _onlineContent.MaxUsers.HasValue ? _onlineContent.MaxUsers.Value : 0;
            maxHours = _onlineContent.MaxHours.HasValue ? _onlineContent.MaxHours.Value : 0;
            neenMoney = _onlineContent.NeedMoney;
            //
            currentViewers = onlineContent.OnlineContentPlays.Count();
            Categories = onlineContent.OnlineCategorizations.Where(c => c.OnlineContentId == onlineContent.Id);

			Author = onlineContent.Client;
            m_AutorRating = Author.m_Rating;
            c_AutorRating = Author.c_Rating;
			BroadcastType = (BroadcastType) onlineContent.BroadcastType;
            Views_online = onlineContent.Views_online;
            Views_anonce = onlineContent.Views_anonce;
            Views_history = onlineContent.Views_history;
            CollectedMoney = onlineContent.CollectedMoney;
            CollectedMoneyExt = onlineContent.CollectedMoneyExt;
			UsePassword = !string.IsNullOrEmpty(onlineContent.Password);
			OnlineContentType = onlineContent.OnlineContentType;
			VideoContentType = onlineContent.VideoContentType;
			HistoryFiles = onlineContent.OnlineContentHistories;
            DownloadUrl = HistoryFiles.Count() > 0 ?
                HistoryFiles.FirstOrDefault().FilePath
                :
                "visell.mp4";
            
			OnlinePlay = onlineContent.OnlineContentPlays;

            Claims = onlineContent.Claims;
            country = onlineContent.Country.Name;
            useHistory = onlineContent.AutoHistory == null ? false : onlineContent.AutoHistory.Value;
            Price = onlineContent.Price;
			if (Price > 0)
				TeamRemainedCount = TeamCount - onlineContent.Paids.Count;

			if (onlineContent.TeamDocs.Any())
			{
				TeamDocuments = onlineContent.TeamDocs.AsEnumerable();
			}

			if (onlineContent.OnlineRatings.Any())
			{
				Comments = onlineContent.OnlineRatings.AsEnumerable();
			}

			//if (OnlineContentType == OnlineContentType.Online || OnlineContentType == OnlineContentType.History)
			{
				Likes = onlineContent.OnlineRatings.Where(m=>m.Like == 1).Count();
                Unlikes = onlineContent.OnlineRatings.Where(m => m.Unlike == 1).Count();
            }

			if (onlineContent.MinimalPrice.HasValue && onlineContent.MinimalPrice.Value > 0 && !IsAnonymous)
			{
				IsPaid = onlineContent.Paids.SingleOrDefault(x => x.UserId == CurrentMembershipUser.UserId) != null;
			}

            BroadcastStart = onlineContent.broadcastStart;
            BroadcastEnd = onlineContent.broadcastEnd;
            IsWaitingAnnouncement = onlineContent.IsWaitingAnnouncement;
		    if (IsWaitingAnnouncement)
            {
                //TimeSpan ts = DateTime.Now - BroadcastStart;
                setTimer = (long)(DateTime.Now - BroadcastStart).TotalMilliseconds;

                if (Author.UserId != CurrentUserId)
                    setTimer = setTimer - 5000;
                if (setTimer < 0)
                    setTimer = 0;
                if (setTimer == 0)
                    IsWaitingAnnouncement = false;
            }
            else
                setTimer = 0;
            CultureImage = onlineContent.CultureImage;
            lenHistory = onlineContent.lenHistory;
            WaitCount = onlineContent.WaitCount;

			Tags = onlineContent.OnlineContentTags.Any()
				               ? new List<string>(onlineContent.OnlineContentTags.Select(x => x.Tag.Name).OrderBy(x => x))
				               : new List<string>();
            
		}
	}
}